package proj.pt.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;

import proj.pt.model.Course;
import proj.pt.model.Department;
import proj.pt.model.SubCourse;
import proj.pt.model.User;
import proj.pt.services.Role;

public class UserListController extends CustomSimpleFormController {

	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		UserFilter filter = (UserFilter)command;
		
		dataMap.put("roleMap", Role.getRoleMap());
		dataMap.put("departments", getLogicProcessor().getDepartments());
		User currentUser = (User)dataMap.get("currentUser");
		dataMap.put("courses", getLogicProcessor().getCourses(currentUser));
		dataMap.put("semesters", getLogicProcessor().getSubCourses(filter.getCourse()));
		
		String action = WebUtils.getAction(request);
		
		if(errors.getErrorCount() < 1 && "action_show".equals(action)){
			dataMap.put("users", getLogicProcessor().getUsers((UserFilter)command));
		} //end if
		
		return dataMap;
	} //end referenceData
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(SubCourse.class, "subCourse", new SubCourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Course.class, "course", new CourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Department.class, "department", new DepartmentEditor(getLogicProcessor()));
	}
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// if no validation required, then just return from this method.
		if(!doValidate(request))return;
		
		String action = WebUtils.getAction(request);
		
		UserFilter filter = (UserFilter)command;
		
		if(UserFilter.USER_ADMIN.equals(filter.getUserType())){
			
		} else if(UserFilter.USER_STAFF.equals(filter.getUserType())){
			if(filter.getDepartment() == null){
				errors.reject("department.required", "Please select a department.");
			} //end if
		} else if(UserFilter.USER_STUDENT.equals(filter.getUserType())){
			if(filter.getCourse() == null){
				errors.reject("course.required", "Please select a course.");
			} else if(filter.getSubCourse() == null){
				errors.reject("semester.required", "Please select a semester.");
			} //end else if
		} //end else if
	}
	
}
